<template>
  <view class="vmall-search" :class="{ 'popup-show': popupShow }">
    <StatusBar />
    <view class="header">
      <up-search placeholder="搜索产品名称、款号" v-model="keyword" @custom="onSearch" @search="onSearch" @clear="onClearSearch" />
    </view>
    <view class="search-result" :class="{ 'search-sesult-index': popupShow }" v-if="isSearchResult">
      <view v-for="(items, index) in goodsList" :key="index" class="goods-item">
        <ShopCard class="items" :item="items" />
      </view>
      <up-divider v-if="goodsList.length>pageSize"  :text="loadStatus"></up-divider>
    </view>
    <view class="history" v-else>
      <view class="flex items-center justify-between mt-24">
        <view class="historytitle">历史记录</view>
        <image v-if="historyList.length>0" class="right-icon" :src="IMG_URL2 + 'common/delete.svg'" @click="clearHistory" />
      </view>
      <view class="content">
        <view class="item" v-for="(item, index) in historyList" :key="index" @click="onSearch(item, 'btn')">
          {{ formatItem(item) }}
        </view>
        
      </view>
    </view>
    <BackTop :backTop="backTop" />
  </view>
</template>

<script setup>
import { IMG_URL2 } from "@/config";
import StatusBar from "@/components/status-bar.vue";
import BackTop from "@/components/back-top.vue";
import ShopCard from "@/components/shop/card.vue";
import { shopApi } from "@/api";


const keyword = ref("");
const historyList = ref([]);
const isSearchResult = ref(false);
const popupShow = ref(false);
const offsetTop = ref("0");

const flowList = ref([]);
let pageSize = ref(10)
let currentPage = ref(1)
let totalCount = ref(0)
let loadStatus =ref('正在加载中')
const goodsList = ref([]);
// 返回顶部
const backTop = ref(0);
const getData = (name,type)=>{
  let data={
    currentPage: currentPage.value,
    name: name,
    pageSize: pageSize.value
  }
  shopApi.CATEGORYGETFRONTPRODUCTLIST(data).then((res) => {
    if(res.code==200){
      
      totalCount.value=res.result.totalCount
      if(type==1){
        goodsList.value=res.result.data
      }else{
        goodsList.value=res.result.data?goodsList.value.concat(res.result.data):[]
      }
    }else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }
    
  })
}
onLoad(() => {
  // #ifdef H5
  offsetTop.value = "-44";
  // #endif
  // #ifdef APP-PLUS
  offsetTop.value = plus.navigator.getStatusbarHeight().toString();
  // #endif
  uni.getStorage({
    key: "historyList",
    success: (res) => {
      historyList.value = res.data == null ? [] : res.data;
    }
  });
});

// 搜索
const onSearch = (value, type) => {
  keyword.value = value;
  if (!type && value) {
    console.log("history", historyList.value);
    const index = historyList.value.indexOf(value);
    if (index == -1) {
      historyList.value.push(keyword.value);
      uni.setStorage({
        key: "historyList",
        data: historyList.value,
        success: () => { }
      });
    }
  }
  currentPage.value=1
  getData(value,1)
  isSearchResult.value = true;
};

// 清除搜索条件
const onClearSearch = () => {
  keyword.value = "";
  isSearchResult.value = false;
};

// 清除搜索历史
const clearHistory = () => {
  historyList.value = [];
  uni.removeStorage({
    key: "historyList",
    success: () => { }
  });
};

// 超过指定长度格式化
const formatItem = (item) => {
  const length = item.length;
  return length > 23 ? item.substr(1, 11) + "..." + item.substr(-11, 11) : item;
};

// 监听页面滚动(tabs吸顶, 返回顶部)
onPageScroll((e) => {
  backTop.value = e.scrollTop;
});

// 触底加载
onReachBottom(() => {
  console.log("触底加载");
  if (goodsList.value.length >= totalCount.value) {
    loadStatus.value = "没有更多数据了";
    return;
  }
  loadStatus.value = "正在加载中";
  currentPage.value++
  getData(keyword.value,2);
});
// 下拉刷新
onPullDownRefresh(() => {
  console.log("下拉刷新");
  // 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
  loadStatus.value = "正在加载中";
  flowList.value = [];
  getData(keyword.value,1);
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 300);
});
</script>

<style lang="scss">
// APP窗口背景色默认白色，需用此种方式调整窗口背景色
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
.vmall-search {
  background-color: #fff;
  height: 100vh;
  .header {
    position: sticky;
    top: 0;
    display: flex;
    justify-content: space-between;
    padding: 12rpx 24rpx;
    box-sizing: border-box;
    background: #ffffff;
    z-index: 10090;
    /* #ifdef APP-PLUS */
    margin-top: var(--status-bar-height);
    /* #endif */
    .arrow-left {
      margin-right: 20rpx;
    }
  }

  .search-result {
    position: relative;
    background-color: #f3f3f3;
    padding: 24rpx;
    box-sizing: border-box;
    .goods-item{
      border-radius: 12rpx;
      overflow: hidden;
      margin-bottom: 24rpx;
    }
  }

  .search-sesult-index {
    z-index: 100100;
  }

  .history {
    padding: 24rpx;
    box-sizing: border-box;
    .historytitle{
      font-family: PingFang SC;
      font-size: 18px;
      font-weight: 600;
      line-height: 26px;
      text-align: left;
      text-underline-position: from-font;
      text-decoration-skip-ink: none;
      color: rgba(0, 0, 0, 0.9);
      margin-bottom: 24rpx;
    }
    .right-icon{
      width: 40rpx;
      height: 40rpx;
    }
    .content {
      padding: 0rpx 10rpx 0rpx 30rpx;
      box-sizing: border-box;
    }

    .item {
      display: inline-block;
      margin: 0rpx 20rpx 20rpx 0rpx;
      padding: 12rpx 24rpx;
      box-sizing: border-box;
      background: rgba(243, 243, 243, 1);
      font-size: 26rpx;
      border-radius: 6rpx;
    }

    .item:active {
      background: #ededed;
    }
  }
}

.popup-show {
  overflow: hidden;
  position: fixed;
}
</style>
